<?php
/**
 * @version : 1.0
 * @since June-2008
 * @package : lib
 * @subpackage struct
 * @name :  CImage
 * @todo:  Lớp  cơ sở CMail. Gửi mail bằng SMTP của Gmail
 *
*/

class CExcel {
	public $table;
	public $file_name;
	public $items;
	function __construct($table, $file_name) {
		$this->table = $table;
		$this->file_name=$file_name;
	}

	function excel_header() {
		header("Content-Type: application/vnd.ms-excel; name='excel';  charset='utf-8'");
		header("Content-Disposition: attachment; filename=".$this->file_name.".xls;");
		header("Pragma: no-cache");
		header("Expires: 0");
	}

	function export_content($content) {
		$this->excel_header();
		echo $content;
	}

	function export($fields_title,$field,$condition=false,$order_by='',$rec_no=65000,$indexing=true) {
		$this->excel_header();
		$paramField = $field;
		$fields_title = explode(',',str_replace(' ','',$fields_title));
		if(is_string($field)){
			$fields = explode(',',str_replace(' ','',$field));
			//$status = 'string';
		}
		if(is_array($field)){
			foreach($field as $k => $v){
				if(is_int($k)){
					$fields[] = $v;
				}else{
					$fields[] = $k;
				}
			}
			//$status = 'array';
		}

		echo '<table border=1><tbody><tr>';
		if ($indexing)
			echo ('<td align="center">STT</td>');

		foreach ($fields_title as $field){
			echo '<td align="center"><strong>'.$field.'</strong></td>';
		}
		echo '</tr>';
		if (!empty($order_by))
			$params=array(
				'order_by' => $order_by,
				'items_per_page' => $rec_no,
				'fields' => $fields
			);
		else
			$params=array(
				'items_per_page' => $rec_no,
				'fields' => $fields
			);
			require_once('lib/data/CStore.php');
		if($items = $this->get_list($this->table, $condition,$params, $paramField)){
			$i=0;
			foreach($items as $k => $item){
				echo '<tr>';
				if ($indexing){
					$i++;
					echo ('<td align="center">'.$i.'</td>');
				}
				foreach ($fields as $field){
					echo '<td align="left">'.(empty($item[$field])?"&nbsp;":$item[$field]).'</td>';
				}
				echo '</tr>';
			}
		}
		echo '</tbody></table>';
	}

	function get_list($table, $condition = '',$params = '', $field = ''){
		if($items = CTable($table)->select_all($condition,$params)){
			foreach($items as $k => &$v){
				if(is_array($field)){
					foreach($field as $kField => $vField){
						if(!is_int($kField)){
							switch($vField[0]){
								case 'date':
									$v[$kField] = CDateTime($v[$kField])->date('d-m-Y');
									break;
								case '':
								default:
									$v[$kField] = $vField[$v[$kField]];
									break;
							}
						}
					}
				}
			}
		}
		return $items;
	}
} // End Class
function CExcel($table, $file_name='ExportExcel')
{
	return new CExcel($table, $file_name);
}
?>